package com.paradox.aggregation.provider.lock;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class LockService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringredisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static String script="local uuid=redis.call('get',KEYS[1]) "+
                                 "local nuuid=tonumber(uuid) "+
                                 "local input=tonumber(ARGV[1]) "+
                                 "if nuuid==input "+
                                 "then redis.call('del',KEYS[1]) "+
                                 "return true "+
                                 "end "+
                                 "return false";
    private static RedisScript<Boolean> redisScript=new DefaultRedisScript<Boolean>(script,Boolean.class);

    public String manulRush(){
        String uuid= UUID.randomUUID().toString();
        /*boolean ifLock=false;
        while(true){
            ifLock=redisTemplate.opsForValue().setIfAbsent("lock",uuid,3000, TimeUnit.MILLISECONDS);
            if(!ifLock){
                log.info("抢购失败，正在重试！");
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else break;
        }*/

        /*ifLock=redisTemplate.opsForValue().setIfAbsent("lock",uuid,3000, TimeUnit.MILLISECONDS);
        if(!ifLock) {
            //log.info("抢购失败！");
            return "抢购失败！";
        }*/

        RLock lock=redissonClient.getLock("lock");
        lock.lock();
        try{
            int remain=Integer.parseInt(redisTemplate.opsForValue().get("stock")+"");
            if(remain>0){
                redisTemplate.opsForValue().decrement("stock");
                log.info("抢购成功，剩余库存："+(remain-1));
                return "抢购成功，剩余库存："+(remain-1);
            }else{
                //log.info("库存不足！");
                return "库存不足！";
            }
        }finally {
            //Boolean res = (Boolean) redisTemplate.execute(redisScript, Lists.newArrayList("lock"), uuid);
            //System.out.println(res);
            lock.unlock();
        }
    }
}
